package com.mallcai.bigdata.ladon.dpl.mapper.peekdata.provider;

import com.mallcai.bigdata.ladon.dpl.entity.peekdata.Tag;
import com.mallcai.bigdata.ladon.dpl.mapper.BaseSqlProvider;
import com.mallcai.bigdata.ladon.dpl.mapper.system.provider.UserSqlProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-06-25 18:53
 */
public class TagSqlProvider extends BaseSqlProvider<Tag> {

    public static final String TB_TAG = "pd_tag";


    @Override
    public String getTableName() {
        return TB_TAG;
    }

    @Override
    public Map<String, String> getInsertColumns() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("name", "#{name}");
        map.put("rule", "#{rule}");
        return map;
    }

    @Override
    public Map<String, String> getUpdateColumns() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("name", "name");
        map.put("rule", "rule");
        return map;
    }


    public String getByParams(Map<String, Object> map) {
        Map<String, Object> params = getParams(map);

        StringBuilder sb = new StringBuilder();
        sb.append("tb_p.archive = 0");
        if (params.containsKey("name") && StringUtils.isNotBlank(params.get("name").toString())) {
            sb.append(" and tb_p.name like concat('%', #{params.name}, '%')");
        }
        if (params.containsKey("createdBy")) {
            sb.append(" and tb_p.created_by = #{params.createdBy}");
        }
        return new SQL() {
            {
                SELECT("tb_p.*, tb_u.nickname AS creator");
                FROM(TB_TAG + " tb_p");
                LEFT_OUTER_JOIN(UserSqlProvider.TB_USER + " tb_u ON tb_u.id = tb_p.created_by ");
                WHERE(sb.toString());
            }
        }.toString();
    }



    /**
     * 根据名称或匹配值查询标签的数量
     * @return
     */
    public String countByNameOrRule(Tag tag){
       StringBuilder sb = new StringBuilder();
       sb.append(" archive = 0 ");
       sb.append(" and (name = #{name} or rule = #{rule})");
       if (tag.getId() != null){
           sb.append(" and id != #{id}");
       }
       return new SQL() {
            {
                SELECT("count(1)");
                FROM(TB_TAG + " tb_m");
                WHERE(sb.toString());
            }
        }.toString();
    }



}
